<template>
  <div class="song-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>歌曲管理</h2>
    </div>

    <!-- 操作栏 -->
    <div class="operation-bar">
      <!-- 搜索框 -->
      <div class="search-box">
        <el-input
          v-model="searchForm.keyword"
          placeholder="请输入歌曲名称"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button :icon="Search" @click="handleSearch" />
          </template>
        </el-input>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="primary" :icon="Plus" @click="handleAddSong">
          新增歌曲
        </el-button>
        <el-button type="danger" :icon="Delete" @click="handleBatchDelete" :disabled="selectedSongs.length === 0">
          批量删除
        </el-button>
      </div>
    </div>

    <!-- 歌曲表格 -->
    <el-table
      :data="songList"
      style="width: 100%"
      v-loading="loading"
      element-loading-text="加载中..."
      @selection-change="handleSelectionChange"
      border
    >
      <!-- 选择列 -->
      <el-table-column type="selection" width="55" />

      <!-- 歌曲ID -->
      <el-table-column prop="songId" label="ID" width="80" />

      <!-- 歌曲图片 -->
      <el-table-column label="图片" width="120">
        <template #default="scope">
          <div class="song-image">
            <el-image
              :src="getSongImageUrl(scope.row.songPic)"
              class="image-img"
              fit="cover"
              :preview-src-list="[getSongImageUrl(scope.row.songPic)]"
              preview-teleported
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><Picture /></el-icon>
                </div>
              </template>
            </el-image>
            <el-button
              type="primary"
              link
              :icon="Upload"
              @click="handleUpdateImage(scope.row)"
              class="update-image-btn"
            >
              更新
            </el-button>
          </div>
        </template>
      </el-table-column>

      <!-- 歌曲名称 -->
      <el-table-column prop="songName" label="歌曲名称" min-width="150" show-overflow-tooltip />

      <!-- 歌手 -->
      <el-table-column label="歌手" width="120">
        <template #default="scope">
          <span v-if="singerMap[scope.row.singerId]">
            {{ singerMap[scope.row.singerId].singerName }}
          </span>
          <span v-else>
            {{ scope.row.singerId }}
          </span>
        </template>
      </el-table-column>

      <!-- 专辑 -->
      <el-table-column prop="songAlbum" label="专辑" width="150" show-overflow-tooltip />

      <!-- 创建时间 -->
      <el-table-column prop="createTime" label="创建时间" width="120">
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button
            type="primary"
            link
            :icon="VideoPlay"
            @click="handlePlaySong(scope.row)"
          >
            播放
          </el-button>
          <el-button
            type="primary"
            link
            :icon="Edit"
            @click="handleEditSong(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            type="danger"
            link
            :icon="Delete"
            @click="handleDeleteSong(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[5, 10, 20, 50]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑歌曲对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        :model="songForm"
        :rules="songRules"
        ref="songFormRef"
        label-width="100px"
      >
        <el-form-item label="歌曲名称" prop="songName">
          <el-input v-model="songForm.songName" placeholder="请输入歌曲名称" />
        </el-form-item>

        <el-form-item label="歌手" prop="singerId">
          <el-select
            v-model="songForm.singerId"
            placeholder="请选择歌手"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="singer in singerList"
              :key="singer.singerId"
              :label="singer.singerName"
              :value="singer.singerId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="专辑" prop="songAlbum">
          <el-input v-model="songForm.songAlbum" placeholder="请输入专辑名称" />
        </el-form-item>

        <el-form-item label="歌词" prop="songLyr">
          <el-input
            v-model="songForm.songLyr"
            type="textarea"
            :rows="4"
            placeholder="请输入歌词"
          />
        </el-form-item>

        <el-form-item label="歌曲文件" v-if="!isEdit">
          <el-upload
              class="song-uploader"
              drag
              :action="uploadSongUrl"
              :headers="uploadHeaders"
              :show-file-list="false"
              :on-success="handleSongSuccess"
              :on-error="handleSongError"
              :before-upload="beforeSongUpload"
              :http-request="customUpload"
          :auto-upload="true"
          >
          <el-icon class="song-uploader-icon"><Upload /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              只能上传mp3文件，且不超过10MB
            </div>
          </template>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitSongForm" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 图片上传对话框 -->
    <el-dialog
        title="更新图片"
        v-model="imageDialogVisible"
        width="400px"
    >
      <div class="image-upload-container">
        <el-upload
            class="image-uploader"
            drag
            :action="uploadImageUrl"
            :headers="uploadHeaders"
            :data="{ id: currentSong?.songId }"
            :show-file-list="false"
            :on-success="handleImageSuccess"
            :on-error="handleImageError"
            :before-upload="beforeImageUpload"
        >
          <el-icon class="image-uploader-icon"><Plus /></el-icon>
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              只能上传jpg/png文件，且不超过2MB
            </div>
          </template>
        </el-upload>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Plus,
  Delete,
  Edit,
  VideoPlay,
  Upload,
  Picture
} from '@element-plus/icons-vue'
import { usePlayerStore } from '@/store/player'
import api from '@/services/api'
import axios from 'axios'
import songDefaultImage from '@/assets/img/song-default.png'
import { useRoute, useRouter } from "vue-router"

export default {
  name: 'SongPage',
  components: {
    Search,
    Plus,
    Delete,
    Edit,
    VideoPlay,
    Upload,
    Picture
  },
  setup() {
    // 加载状态
    const loading = ref(false)
    const submitLoading = ref(false)

    const router = useRouter()
    const route = useRoute()

    // 搜索表单
    const searchForm = reactive({
      keyword: ''
    })

    // 歌曲列表
    const songList = ref([])

    // 歌手列表（用于选择）
    const singerList = ref([])

    // 歌手映射（用于显示歌手名称）
    const singerMap = ref({})

    // 选中的歌曲
    const selectedSongs = ref([])

    // 分页信息
    const pagination = reactive({
      currentPage: 1,
      pageSize: 5,
      total: 0
    })

    // 对话框相关
    const dialogVisible = ref(false)
    const dialogTitle = ref('')
    const isEdit = ref(false)

    // 图片上传对话框
    const imageDialogVisible = ref(false)
    const currentSong = ref(null)

    // 歌曲表单
    const songForm = reactive({
      songId: null,
      songName: '',
      singerId: null,
      songPic: '',
      songAlbum: '',
      songLyr: '',
      songUrl: ''
    })

    // 表单验证规则
    const songRules = {
      songName: [
        { required: true, message: '请输入歌曲名称', trigger: 'blur' }
      ],
      singerId: [
        { required: true, message: '请选择歌手', trigger: 'change' }
      ]
    }

    // 表单引用
    const songFormRef = ref(null)

    // 默认图片
    const defaultImage = songDefaultImage

    // 上传相关配置
    const uploadSongUrl = '/api/song/add'
    const uploadImageUrl = '/api/song/songOfPic'
    const uploadHeaders = {
      Authorization: localStorage.getItem('adminToken')
    }

    // 上传额外数据
    const uploadExtraData = reactive({
      singerId: '',
      songName: '',
      songAlbum: '',
      songLyr: '',
      songUrl: ''
    })

    // 播放器状态管理
    const playerStore = usePlayerStore()

    /**
     * 格式化日期
     * @param {string} date - 日期字符串
     * @returns {string} 格式化后的日期
     */
    const formatDate = (date) => {
      if (!date) return ''
      return date.split(' ')[0]
    }

    /**
     * 获取歌曲列表
     */
    const fetchSongList = async () => {
      loading.value = true
      try {
        let response
        // 检查是否有歌手ID查询参数
        const singerId = route.query.singerId
        if (singerId) {
          // 根据歌手ID获取歌曲
          response = await api.song.getBySingerId(singerId)
        } else if (searchForm.keyword) {
          // 模糊搜索
          response = await api.song.search(searchForm.keyword)
        } else {
          // 获取所有歌曲
          response = await api.song.getAll({
            page: pagination.currentPage,

            size: pagination.pageSize
          })
        }

        if (response.code === '1') {
          songList.value = response.data || []
          pagination.total = songList.value.length

          // 获取所有歌手信息用于显示
          await fetchSingerList()
        } else {
          ElMessage.error(response.msg || '获取歌曲列表失败')
          songList.value = []
          pagination.total = 0
        }
      } catch (error) {
        ElMessage.error('获取歌曲列表失败')
        console.error('Fetch song list error:', error)
      } finally {
        loading.value = false
      }
    }

    /**
     * 获取歌手列表
     */
    const fetchSingerList = async () => {
      try {
        const response = await api.singer.getAll()
        if (response.code === '1') {
          singerList.value = response.data || []
          // 构建歌手映射
          const map = {}
          if (response.data && Array.isArray(response.data)) {
            response.data.forEach(singer => {
              if (singer && typeof singer === 'object' && singer.singerId !== undefined) {
                map[singer.singerId] = singer
              }
            })
          }
          singerMap.value = map
        }
      } catch (error) {
        console.error('Fetch singer list error:', error)
      }
    }

    /**
     * 处理搜索
     */
    const handleSearch = () => {
      pagination.currentPage = 1
      fetchSongList()
    }

    /**
     * 处理选择变化
     * @param {Array} selection - 选中的行
     */
    const handleSelectionChange = (selection) => {
      selectedSongs.value = selection
    }

    /**
     * 处理分页大小变化
     * @param {number} val - 每页条数
     */
    const handleSizeChange = (val) => {
      pagination.pageSize = val
      pagination.currentPage = 1
      fetchSongList()
    }

    /**
     * 处理当前页变化
     * @param {number} val - 当前页码
     */
    const handleCurrentChange = (val) => {
      pagination.currentPage = val
      fetchSongList()
    }

    /**
     * 处理新增歌曲
     */
    const handleAddSong = () => {
      dialogTitle.value = '新增歌曲'
      isEdit.value = false
      // 重置表单
      Object.assign(songForm, {
        songId: null,
        songName: '',
        singerId: null,
        songAlbum: '',
        songLyr: '',
        songUrl: ''
      })
      dialogVisible.value = true
    }

    /**
     * 处理编辑歌曲
     * @param {Object} row - 歌曲数据
     */
    const handleEditSong = (row) => {
      dialogTitle.value = '编辑歌曲'
      isEdit.value = true
      // 填充表单数据
      Object.assign(songForm, {
        songId: row.songId,
        songName: row.songName,
        singerId: row.singerId,
        songAlbum: row.songAlbum,
        songLyr: row.songLyr,
        songUrl: row.songUrl
      })
      dialogVisible.value = true
    }

    /**
     * 处理播放歌曲
     * @param {Object} row - 歌曲数据
     */
    const handlePlaySong = async (row) => {
      // 获取完整歌曲信息（包含歌词）
      try {
        const response = await api.song.getById(row.songId)
        if (response.code === '1') {
          const song = response.data
          // 构造歌曲对象
          const songObj = {
            id: song.songId,
            name: song.songName,
            singerName: singerMap.value[song.singerId]?.singerName || '未知歌手',
            url: song.songUrl,
            picUrl: song.songPic || defaultImage,
            lyrics: song.songLyr || ''
          }

          // 设置当前播放歌曲
          playerStore.setCurrentSong(songObj)
          playerStore.setPlayingStatus(true)

          ElMessage.success('开始播放')
        }
      } catch (error) {
        console.error('获取歌曲详情失败:', error)
        // 如果获取详情失败，使用基础信息播放
        const song = {
          songId: row.songId,
          songName: row.songName,
          singerName: singerMap.value[row.singerId]?.singerName || '未知歌手',
          songUrl: row.songUrl,
          songPic: row.songPic || defaultImage,
          songLyr: row.songLyr || ''
        }

        playerStore.setCurrentSong(song)
        playerStore.setPlayingStatus(true)
        ElMessage.success('开始播放')
      }
    }

    /**
     * 处理删除歌曲
     * @param {Object} row - 歌曲数据
     */
    const handleDeleteSong = async (row) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除歌曲 "${row.songName}" 吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        const response = await api.song.delete(row.songId)
        if (response.code === '1') {
          ElMessage.success('删除成功')
          await fetchSongList()
        } else {
          ElMessage.error(response.msg || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    /**
     * 处理批量删除
     */
    const handleBatchDelete = async () => {
      if (selectedSongs.value.length === 0) {
        ElMessage.warning('请先选择要删除的歌曲')
        return
      }

      try {
        await ElMessageBox.confirm(
          `确定要删除选中的 ${selectedSongs.value.length} 首歌曲吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        // 批量删除
        const deletePromises = selectedSongs.value.map(song =>
          api.song.delete(song.songId)
        )

        const results = await Promise.all(deletePromises)
        const successCount = results.filter(result => result.code === '1').length

        if (successCount > 0) {
          ElMessage.success(`成功删除 ${successCount} 首歌曲`)
          await fetchSongList()
        } else {
          ElMessage.error('删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    /**
     * 处理更新图片
     * @param {Object} row - 歌曲数据
     */
    const handleUpdateImage = (row) => {
      currentSong.value = row
      imageDialogVisible.value = true
    }

    /**
     * 歌曲上传前检查
     * @param {File} file - 上传的文件
     * @returns {boolean} 是否允许上传
     */
    const beforeSongUpload = (file) => {
      const isMP3 = file.type === 'audio/mpeg' || file.name.endsWith('.mp3')
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isMP3) {
        ElMessage.error('歌曲文件只能是 MP3 格式!')
        return false
      }
      if (!isLt10M) {
        ElMessage.error('歌曲文件大小不能超过 10MB!')
        return false
      }

      // 验证表单数据
      if (!songForm.songName || !songForm.singerId) {
        ElMessage.error('请填写完整的歌曲信息!')
        return false
      }

      return true
    }

    /**
     * 图片上传前检查
     * @param {File} file - 上传的文件
     * @returns {boolean} 是否允许上传
     */
    const beforeImageUpload = (file) => {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        ElMessage.error('图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!')
      }

      return isJPG && isLt2M
    }

    /**
     * 歌曲上传成功处理
     * @param {Object} response - 上传响应
     */
    const handleSongSuccess = (response, file, fileList) => {
      console.log('Upload success response:', response)
      // 确保 response 存在再访问其属性
      if (response && response.code === '1') {
        ElMessage.success('歌曲上传成功')
        dialogVisible.value = false
        fetchSongList()
      } else {
        // 提供更详细的错误信息
        const errorMsg = (response && response.msg) || '歌曲上传失败'
        ElMessage.error(errorMsg)
        console.error('Upload failed with response:', response)
      }
    }

    /**
     * 歌曲上传失败处理
     * @param {Error} error - 错误信息
     */
    const handleSongError = (error, file, fileList) => {
      console.error('Song upload error:', error)
      // 更安全的错误信息提取
      let errorMessage = '歌曲上传失败'
      if (error && error.response && error.response.data) {
        errorMessage = error.response.data.msg || errorMessage
      } else if (error && error.message) {
        errorMessage = error.message
      }
      ElMessage.error(errorMessage)
    }

    /**
     * 图片上传成功处理
     * @param {Object} response - 上传响应
     */
    const handleImageSuccess = (response) => {
      if (response.code === '1') {
        ElMessage.success('图片更新成功')
        imageDialogVisible.value = false
        fetchSongList()
      } else {
        ElMessage.error(response.msg || '图片更新失败')
      }
    }

    /**
     * 图片上传失败处理
     * @param {Error} error - 错误信息
     */
    const handleImageError = (error) => {
      ElMessage.error('图片上传失败')
      console.error('Image upload error:', error)
    }

    /**
     * 获取歌曲图片URL
     * @param {string} imagePath - 图片路径
     * @returns {string} 图片URL
     */
    const getSongImageUrl = (imagePath) => {
      if(!imagePath) return defaultImage

      if(imagePath.startsWith('http')){
        return imagePath
      }

      if(imagePath.startsWith('/')){
        return imagePath
      }

      if(imagePath.startsWith('img/')){
        return `/${imagePath}`
      }

      return defaultImage
    }

    /**
     * 获取上传数据
     * @returns {Object} 上传数据
     */
    const getUploadData = () => {
      return {
        songName: songForm.songName,
        singerId: songForm.singerId,
        songAlbum: songForm.songAlbum || '',
        songLyr: songForm.songLyr || ''
      }
    }

    /**
      * 自定义上传歌曲
      */
    const customUpload = async (options) => {
      const { file } = options

      // 验证表单数据
      if (!songForm.songName || !songForm.singerId) {
        ElMessage.error('请填写完整的歌曲信息!')
        return Promise.reject(new Error('表单数据不完整'))
      }

      // 创建 FormData 对象
      const formData = new FormData()
      formData.append('file', file)
      formData.append('songName', songForm.songName)
      formData.append('singerId', songForm.singerId)
      formData.append('songAlbum', songForm.songAlbum || '')
      formData.append('songLyr', songForm.songLyr || '')

      try {
        // 直接使用 axios 发送请求，避免 api.js 中的拦截器干扰
        const response = await axios.post('/api/song/add', formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
            'Authorization': localStorage.getItem('adminToken')
          }
        })

        handleSongSuccess(response.data, file, null)
        return response.data
      } catch (error) {
        console.error('Upload error:', error)
        // 提取更详细的错误信息
        let errorMessage = '歌曲上传失败'
        if (error.response && error.response.data) {
          errorMessage = error.response.data.msg || error.response.data.message || errorMessage
        } else if (error.message) {
          errorMessage = error.message
        }
        ElMessage.error(errorMessage)
        handleSongError(error, file, null)
        throw error
      }
    }

    /**
     * 提交歌曲表单
     */
    const submitSongForm = async () => {
      if (!songFormRef.value) return

      await songFormRef.value.validate(async (valid) => {
        if (valid) {
          if (isEdit.value) {
            // 编辑歌曲逻辑
            submitLoading.value = true
            try {
              const formData = {
                songId: songForm.songId,
                songName: songForm.songName,
                singerId: songForm.singerId,
                songAlbum: songForm.songAlbum || '',
                songLyr: songForm.songLyr || ''
              }

              const response = await api.song.update(formData)
              if (response.code === '1') {
                ElMessage.success('编辑成功')
                dialogVisible.value = false
                await fetchSongList()
              } else {
                ElMessage.error(response.msg || '编辑失败')
              }
            } catch (error) {
              ElMessage.error('编辑失败: ' + (error.message || '未知错误'))
              console.error('Edit song error:', error)
            } finally {
              submitLoading.value = false
            }
          } else {
            // 新增歌曲通过上传组件处理，不需要手动提交表单
            ElMessage.info('请通过拖拽或点击上传歌曲文件')
          }
        }
      })
    }

    /**
     * 处理对话框关闭
     */
    const handleDialogClose = () => {
      if (songFormRef.value) {
        songFormRef.value.resetFields()
      }
    }

    // 组件挂载时获取数据
    onMounted(() => {
      fetchSongList()
    })

    return {
      loading,
      submitLoading,
      searchForm,
      songList,
      singerList,
      singerMap,
      selectedSongs,
      pagination,
      dialogVisible,
      dialogTitle,
      isEdit,
      imageDialogVisible,
      songForm,
      songRules,
      songFormRef,
      defaultImage,
      uploadSongUrl,
      uploadImageUrl,
      uploadHeaders,
      uploadExtraData,
      currentSong,
      formatDate,
      handleSearch,
      handleSelectionChange,
      handleSizeChange,
      handleCurrentChange,
      handleAddSong,
      handleEditSong,
      handlePlaySong,
      handleDeleteSong,
      handleBatchDelete,
      handleUpdateImage,
      beforeSongUpload,
      beforeImageUpload,
      handleSongSuccess,
      handleSongError,
      handleImageSuccess,
      handleImageError,
      submitSongForm,
      handleDialogClose,
      getSongImageUrl,
      getUploadData,
      customUpload
    }
  }
}
</script>

<style scoped>
.song-container {
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.search-box {
  width: 300px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.song-image {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.image-img {
  width: 80px;
  height: 80px;
  border-radius: 5px;
}

.update-image-btn {
  margin-top: 5px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.image-upload-container,
.song-uploader {
  text-align: center;
}

.image-uploader .image-uploader-icon,
.song-uploader .song-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
  line-height: 120px;
}

.image-uploader :deep(.el-upload),
.song-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.image-uploader :deep(.el-upload:hover),
.song-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}
</style>
